package com.sensetime.jv.exception.handler;

import com.sensetime.jv.entity.ReturnWrapper;
import com.sensetime.jv.enums.StatusEnum;
import com.sensetime.jv.exception.CustomException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;
import java.util.Set;

@RestControllerAdvice
@Slf4j
public class CustomExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public ReturnWrapper handle(Throwable e){
        log.error(e.getMessage(), e);

        if (e instanceof CustomException) {
            return ReturnWrapper.error(((CustomException) e).getStatus()).msg(e.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            String firstMsg = Objects.requireNonNull(((MethodArgumentNotValidException) e).getBindingResult()
                            .getFieldError())
                    .getDefaultMessage();
            return ReturnWrapper.error(StatusEnum.PARAMS_ERROR).msg(firstMsg);
        } else if (e instanceof ConstraintViolationException) {
            Set<ConstraintViolation<?>> violations = ((ConstraintViolationException) e).getConstraintViolations();
            String firstMsg = violations.stream()
                    .findFirst()
                    .map(ConstraintViolation::getMessage)
                    .orElse("参数校验失败");
            return ReturnWrapper.error(StatusEnum.PARAMS_ERROR).msg(firstMsg);
        } else {
            return ReturnWrapper.error(StatusEnum.INTERNAL_ERROR);
        }
    }
}